<?php
// 【终极修复版 - 简化并修正Session配置】common/session_config.php

// 1. Session配置
if (session_status() == PHP_SESSION_NONE) {
    
    // 设置一个所有脚本都能访问的、安全的session存储路径
    $session_path = realpath(__DIR__ . '/../../sessions');
    if (!is_dir($session_path)) { 
        @mkdir($session_path, 0777, true); 
    }
    if (is_dir($session_path) && is_writable($session_path)) {
        session_save_path($session_path);
    }
    
    // 【核心修正】采用最通用的Cookie参数设置，不再指定domain
    // 这会让Cookie只对当前访问的地址（无论是IP还是域名）生效
    session_set_cookie_params(
        0,                                                  // cookie生命周期 (0 = 关闭浏览器失效)
        '/',                                                // cookie有效路径 ('/' = 整个站点)
        "",                                                 // domain参数留空，这是关键！
        isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] != 'off', // secure标志
        true                                                // HttpOnly标志
    );
    
    // 启动或恢复session
    session_start();
}


// 2. Token验证函数
function verify_token($token) {
    $secret_key = 'kkcc.vip-is-the-best-!@#$%'; // !!重要!! 密钥
    if (!$token) return null;
    $token_parts = explode('.', $token);
    if (count($token_parts) !== 3) return null;
    list($base64UrlHeader, $base64UrlPayload, $base64UrlSignature) = $token_parts;
    $signature = base64_decode(str_replace(['-', '_'], ['+', '/'], $base64UrlSignature));
    $expectedSignature = hash_hmac('sha256', $base64UrlHeader . "." . $base64UrlPayload, $secret_key, true);
    if (!hash_equals($expectedSignature, $signature)) return null;
    $payload_decoded = json_decode(base64_decode(str_replace(['-', '_'], ['+', '/'], $base64UrlPayload)), true);
    if ($payload_decoded === null || ($payload_decoded['exp'] ?? 0) < time()) return null;
    return $payload_decoded['data'];
}

// 3. 兼容所有环境的获取请求头函数
function get_authorization_header() {
    $headers = null;
    if (isset($_SERVER['Authorization'])) { $headers = trim($_SERVER["Authorization"]); }
    else if (isset($_SERVER['HTTP_AUTHORIZATION'])) { $headers = trim($_SERVER["HTTP_AUTHORIZATION"]); }
    elseif (function_exists('apache_request_headers')) {
        $requestHeaders = apache_request_headers();
        $requestHeaders = array_combine(array_map('ucwords', array_keys($requestHeaders)), array_values($requestHeaders));
        if (isset($requestHeaders['Authorization'])) { $headers = trim($requestHeaders['Authorization']); }
    }
    return $headers;
}

// 4. 强制实名检查函数
function force_rename_check($con, $user_data) {
    if (!$user_data || !isset($user_data['proxy_acc'])) {
        http_response_code(401); echo json_encode(['status' => -99, 'msg' => '登录失效']); exit();
    }
    $proxy_acc_safe = mysqli_real_escape_string($con, $user_data['proxy_acc']);
    $sql = "SELECT proxy_rename_sta, cr_time FROM proxy WHERE proxy_acc = '$proxy_acc_safe'";
    $result = mysqli_query($con, $sql);
    if ($result && $row = mysqli_fetch_assoc($result)) {
        $is_renamed = $row['proxy_rename_sta'];
        $register_time = (int)$row['cr_time'];
        $days_since_register = (time() - $register_time) / (60 * 60 * 24);
        if ($is_renamed == 0 && $days_since_register > 3) {
            http_response_code(403);
            echo json_encode(['status' => -10, 'msg' => '根据平台规定，您必须在注册3日内完成实名认证。']);
            exit();
        }
    } else {
        http_response_code(401); echo json_encode(['status' => -99, 'msg' => '无法验证用户信息']); exit();
    }
}
?>